package com.example.base.configuration;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.base.entity.User;
import com.example.base.service.UserService;
import com.example.base.utils.TokenUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class SessionInterceptor extends HandlerInterceptorAdapter {

    private UserService userService;

    public SessionInterceptor(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e)
            throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mv)
            throws Exception {
    }

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        //跨域的嗅探放行
        if ("OPTIONS".equalsIgnoreCase(req.getMethod())) {
            System.out.println("Method:OPTIONS");
            return true;
        }
        //注册以及登录放行
        System.out.println("req.getRequestURI() = " + req.getRequestURI());
        if ("/register".equals(req.getRequestURI()) || "/user/login".equals(req.getRequestURI()) ||
                "/error".equals(req.getRequestURI())) {
            return true;
        }
        String token = req.getHeader("token");
        if (null == token) {
            verifyFail(resp, "请先登录");
            return false;
        } else {
            String email;
            try {
                email = JWT.decode(token).getClaims().get("email").asString();
            } catch (JWTDecodeException e) {
                verifyFail(resp, "请登录");
                return false;
            }
            User user = userService.getUserByEmail(email);
            if (null == user) {
                verifyFail(resp, "用户不存在，请重新登录");
                return false;
            } else {
                try {
                    TokenUtils.verifyToken(token);
                } catch (JWTVerificationException e) {
                    verifyFail(resp, "验证失败，请重新登录");
                    return false;
                }
            }
        }
        return true;
    }

    private void verifyFail(HttpServletResponse resp, String msg) throws IOException {
        System.out.print(msg);
        resp.setContentType("application/json;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        ObjectMapper objectMapper = new ObjectMapper();
        out.print(objectMapper.writeValueAsString(msg));
    }
}